<template>
  <j-modal
    :title="importStep == 1 ? '批量导入' : importStep == 2 ? '导入信息' : importStep == 3 ? '选择模板发送' : ''"
    :width="importStep == 1 ? 600:width"
    :visible="visible"
    switchFullscreen
    @ok="handleOk"
    :okButtonProps="{ class: { 'jee-hidden': disableSubmit } }"
    @cancel="handleCancel"
    cancelText="关闭"
  >
    <!--//批量导入-->
    <a-spin :spinning="confirmLoading" v-if="importStep == 1">
      <a-upload-dragger
        :multiple="false"
        :accept="accept"
        :fileList="fileListData"
        :remove="handleRemove"
        :beforeUpload="beforeUpload"
      >
        <p class="ant-upload-drag-icon">
          <a-icon type="inbox" />
        </p>
        <p class="ant-upload-text">点击或将文件拖拽到这里上传</p>
        <p class="ant-upload-hint">支持扩展名：{{ accept }}</p>
      </a-upload-dragger>
      <div class="ant-upload-matter">
        <p>注意事项：</p>
        <p>1.请勿修改模版格式，以免导入失败；</p>
      </div>
    </a-spin>
    <!--//导入信息-->
    <div class="modal-status modal-status-finish" v-if="importStep == 2">
      <a-icon class="finish" type="check-circle" theme="filled" />
      <h2>导入完成</h2>
      <h3>手机号已导入完成，是否发送预警短信?</h3>
      <p>
        成功导入<span class="blue">{{ result.phoneSum }}</span> 个手机号，
        有效<span class="blue">{{ result.correctPhoneNum }}</span>个手机号，
        无效<span class="error">{{ result.errorPhoneNum }}</span >个手机号
      </p>
    </div>
    <!--选择模板发送-->
    <div v-if="importStep == 3">
      <z-table
        ref="table"
        rowKey="id"
        :showColSettings="false"
        :showAlert="false"
        :showSelection="true"
        :columns="columns"
        :dataSource="pageData"
        :rowSelection="{ type: 'radio' }"
        @change="onTableChange"
      >
        <span slot="templateContent" slot-scope="text">
          <j-ellipsis :value="text" :length="20" />
        </span>
      </z-table>
    </div>
    <template slot="footer" v-if="importStep == 1">
      <a class="footer-model" @click="downloadTemplate">下载数据模板</a>
      <a-button key="back" @click="handleCancel"> 取消 </a-button>
      <a-button key="submit" type="primary" @click="handleOk"> 开始导入 </a-button>
    </template>
    <template slot="footer" v-else-if="importStep == 2">
      <a-button key="back" @click="handleCancel">取消</a-button>
      <a-button key="submit" type="primary" @click="handleNext">下一步</a-button>
    </template>
    <template slot="footer" v-else-if="importStep == 3">
      <a-button key="prevSubmit" @click="handlePrev" v-if="Object.keys(result).length>0">上一步</a-button>
      <a-button key="back" @click="handleCancel">取消</a-button>
      <a-button key="submit" type="primary" @click="handleSend">发送</a-button>
    </template>
  </j-modal>
</template>

<script>
import * as noteApi from '@/api/modules/note.js'
export default {
  data() {
    return {
      title: '',
      width: 800,
      visible: false,
      disableSubmit: false,
      importStep: 1,
      result: {},
      downloadFileName: '短信速送-导入模板.xls',
      confirmLoading: false,
      fileListData: [],
      accept: '.xls,.xlsx', // 导入的文件格式
      query: {},
      pageFilter: {
        pageNo: 1,
        pageSize: 10,
      },
      pageData: {},
      form: {
        templateType: 1 //模板类型为短信类型
      },
      columns: [
        {
          title: '序号',
          dataIndex: '',
          key: 'rowIndex',
          width: 60,
          align: 'center',
          customRender: function (t, r, index) {
            return parseInt(index) + 1
          },
        },
        {
          title: '模板CODE',
          align: 'center',
          dataIndex: 'templateCode',
        },
        {
          title: '模板标题',
          align: 'center',
          dataIndex: 'templateName',
        },
        {
          title: '模板内容',
          align: 'center',
          dataIndex: 'templateContent',
          scopedSlots: { customRender: 'templateContent' },
        },
      ]
    }
  },
  watch: {
    importStep: {
      immediate: true,
      handler(val) {
        if(val && val==3) this.refreshTable()
      }
    }
  },
  methods: {
    add() {
      this.visible = true
    },
    edit(datas) {
      this.visible = true
      this.query = datas
    },
    close() {
      this.$emit('close')
      this.visible = false
    },
    handleNext() {
      this.importStep++
    },
    handlePrev() {
      this.importStep--
    },
    handleCancel() {
      this.close()
      if(this.importStep>1) this.$emit('ok')
      this.result={}
      this.importStep=1
    },
    // 导入操作
    handleOk() {
      const { fileListData } = this
      if (fileListData && fileListData.length === 0) {
        this.$message.error('请选择导入文件')
        return
      }
      const formData = new FormData()
      fileListData.forEach((file) => {
        formData.append('files', file)
      })
      this.confirmLoading = true
      noteApi
        .importPhoneExcel(formData)
        .then((res) => {
          if (res.success) {
            this.confirmLoading = false
            this.result = res.result
            this.handleNext()
          } else {
            this.confirmLoading = false
            this.$message.error(res.message)
          }
        })
        .catch((e) => {
          this.confirmLoading = false
          this.$message.error('导入出错了')
        })
    },
    // 发送短信操作
    handleSend() {
      let parameter = {}
      let selectedRows = this.$refs.table.getSelectedRows()
      if(selectedRows.length===0) {
        this.$message.warn('请选择一条模板再操作！')
        return
      }
      // 导入成功发送短信
      if (Object.keys(this.result).length>0) {
        parameter = {
          sysMessageTemplate: selectedRows[0],
          idList: Object.keys(this.result).length>0 && this.result.stringList?this.result.stringList:[]
        }
      // 重新发送、发送短信
      } else {
        parameter = {
          sysMessageTemplate: selectedRows[0],
          ...this.query
        }
      }
      // this.$message.warn('此短信功能展未开放')
      noteApi.sendNoteBatch(parameter).then((res) => {
        if (res.success) {
          this.$message.success(res.result)
          this.importStep=1
          this.result={}
          this.$emit('ok')
        } else {
          this.$message.warn(res.result)
        }
      }).catch(e=>{
        this.$message.warn("请求失败！")
      })
    },
    // 下载数据模板
    downloadTemplate() {
      noteApi.exportNoteSendTemplate().then((res) => {
        if (res && res.size > 0) {
          this.downLoadMix(res, this.downloadFileName)
        } else {
          this.$message.warn('模板不存在！')
        }
      })
    },
    // 切换选择模板发送分页
    onTableChange(pagination, pageFilter, sorter) {
      let keyMap = { currentPage: 'pageNo' }
      let paginations = Object.keys(pagination).reduce((newData, key) => {
        let newKey = keyMap[key] || key
        newData[newKey] = pagination[key]
        return newData
      }, {})
      this.pageFilter = Object.assign({}, this.pageFilter, paginations)
      this.refreshTable()
    },
    //选择模板发送列表
    refreshTable() {
      let form = Object.assign({}, this.form, this.pageFilter)
      noteApi
        .sysMessageTemplate(form)
        .then((res) => {
          if (res.success) {
            this.pageData = res.result
            this.$refs.table.onClearRowKeys()
          }
        })
        .catch((e) => {
          this.$message.warn('请求失败！')
        })
    },
    //上传前拦截
    beforeUpload(file) {
      this.fileListData = [file] //[...this.fileListData, file];
      return false
    },
    // 移除
    handleRemove(file) {
      const index = this.fileListData.indexOf(file)
      const newFileList = this.fileListData.slice()
      newFileList.splice(index, 1)
      this.fileListData = newFileList
    },
    downLoadMix(res, fileName) {
      let blob = new Blob([res]) //res为从后台返回的数据
      if (!fileName) {
        fileName = res.headers['content-disposition'].split('filename=').pop()
      }
      if ('msSaveOrOpenBlob' in navigator) {
        window.navigator.msSaveOrOpenBlob(blob, fileName)
      } else {
        const elink = document.createElement('a')
        elink.download = fileName
        elink.style.display = 'none'
        elink.href = URL.createObjectURL(blob)
        document.body.appendChild(elink)
        elink.click()
        URL.revokeObjectURL(elink.href)
        document.body.removeChild(elink)
      }
    }
  }
}
</script>

<style scoped lang="less">
/deep/.ant-upload-matter {
  padding: 30px 0 0;
  p {
    margin-bottom: 0;
  }
}
/deep/.ant-modal-footer {
  position: relative;
  .footer-model {
    position: absolute;
    left: 20px;
    &::before {
      content: '*';
      color: #f5222d;
      margin-right: 5px;
    }
  }
}
.modal-status {
  &.modal-status-finish {
    text-align: center;
    padding: 60px 0;
    .finish {
      font-size: 70px;
      color: #52c41a;
    }
    h2 {
      font-size: 24px;
      font-weight: bold;
      padding: 30px 0 10px;
    }
    h3 {
      font-size: 18px;
      padding-bottom: 10px;
    }
    p {
      font-size: 16px;
    }
  }
  .fail {
    font-size: 70px;
    color: #f5222d;
  }
  .blue {
    color: #02a7f0;
  }
  .error {
    color: #d9001b;
  }
}
</style>
